package com.better.common.config;


import com.better.common.mongo.repository.CommonMongoRepositoryImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * 配置默认的Repository实现类为CommonRepositoryImpl，代替SimpleMongoRepository
 *
 * 同时修改默认的Repository扫描目录为 com.better.common.mongo
 * Created by zengxm on 2016/4/14 0014.
 */
@Configuration
@EnableMongoRepositories(repositoryBaseClass =CommonMongoRepositoryImpl.class, basePackages =("com.better.common.mongo"))
public class MongonDBConfig {
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {
        }

        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return mappingConverter;
    }
}